package bean;

import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;

import javax.jdo.Query;

import pmf.PMF;

public class SearchArt {

	@SuppressWarnings("unchecked")
	public List<Articles> searchByItem(String searchName) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Articles.class);

		query.setFilter("artName == searchName");
		query.setOrdering("buyDate asc");
		query.declareParameters("String searchName");
		try {
			List<Articles> results = (List<Articles>) query.execute(searchName);
			List<Articles> artList = new LinkedList<Articles>();

			for (Articles tempArt : results) {
				Branch branch = tempArt.getBranch();
				
				artList.add(new Articles(tempArt.getKey(), null, null, 
						tempArt.getArtName(), tempArt.getPrice(), null, tempArt.getBuyDate(), 
						new Branch(branch.getKey(), branch.getBranchName()), tempArt.getTotalAmount(), tempArt.getRemainAmount(), tempArt.getLeftAmount(),
						tempArt.getShipFee(), tempArt.getNote()));
			}
			return artList;
		} finally {
			query.closeAll();
			pm.close();
		}
	}
	
	public Articles searchById(long id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Articles art = pm.getObjectById(Articles.class, id);
			Member mem = art.getCreateUserID();
			Category cat = art.getCategory();
			ShipStyle shipWay = art.getShipWay();
			Branch branch = art.getBranch();
			
			Articles saveArt = new Articles(art.getKey(), new Member(mem.getKey(), mem.getUserID(), mem.getName(), mem.getPhone(), mem.getPassword(), mem.getEmail(), mem.getAddress(), mem.isCostcoMem(), mem.isState()),
				new Category(cat.getKey(), cat.getCatName()), art.getArtName(), art.getPrice(),
				new ShipStyle(shipWay.getKey(), shipWay.getShipWay()), art.getBuyDate(),
				new Branch(branch.getKey(), branch.getBranchName()), art.getTotalAmount(), art.getRemainAmount(), art.getLeftAmount(),art.getShipFee(), art.getNote());
			return saveArt;
		} finally{
			pm.close();
		}		
	}

}
